<template>
  <div class="add-card">
    <div class="top">
      <div class="left">
        <arrow-left-outlined />
        <span @click="goBack">返回</span>
        <span>|</span>
        <span>{{ topLeftTitle }}</span>
      </div>
      <div class="right">黑马程序员</div>
    </div>
    <div class="main">
      <div style="padding: 30px 100px">
        <!-- 不管什么框架，有标题有内容的UI结构，首先想到Card组件， elment-ui vant-ui ant-design-vue -->
        <a-card title="车辆信息" :bordered="false">
          <a-form
            :model="formState1"
            name="formState1"
            ref="refForm1"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
          >
            <!-- 表单配合栅格系统的布局，需要去表单组件文档里面 搜索 栅格 两个字。 如果没有就去百度 -->
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="车主姓名"
                  name="personName"
                  :rules="pageType === 3 ? [] : [{ required: true, message: '请填写车主姓名' }]"
                >
                  <span v-if="pageType === 3">{{ formState1.personName }}</span>
                  <a-input
                    v-else
                    v-model:value="formState1.personName"
                    :disabled="pageType === 4"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="联系方式"
                  name="phoneNumber"
                  :rules="pageType === 3 ? [] : [{ required: true, message: '请填写联系方式' }]"
                >
                  <span v-if="pageType === 3">{{ formState1.phoneNumber }}</span>
                  <a-input
                    v-else
                    v-model:value="formState1.phoneNumber"
                    :disabled="pageType === 4"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="车牌号码"
                  name="carNumber"
                  :rules="pageType === 3 ? [] : [{ required: true, message: '请填写车牌号码' }]"
                >
                  <span v-if="pageType === 3">{{ formState1.carNumber }}</span>
                  <a-input v-else v-model:value="formState1.carNumber" :disabled="pageType === 4" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="车牌品牌"
                  name="carBrand"
                  :rules="pageType === 3 ? [] : [{ required: true, message: '请填写车牌品牌' }]"
                >
                  <span v-if="pageType === 3">{{ formState1.carBrand }}</span>
                  <a-input v-else v-model:value="formState1.carBrand" :disabled="pageType === 4" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
      </div>
      <div style="padding: 0 100px">
        <a-card title="最近一次月卡缴费信息" :bordered="false">
          <a-form
            v-if="pageType !== 3"
            :model="formState2"
            name="formState2"
            ref="refForm2"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
          >
            <!-- 表单配合栅格系统的布局，需要去表单组件文档里面 搜索 栅格 两个字。 如果没有就去百度 -->
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="有效日期"
                  name="range-picker"
                  :rules="[{ required: true, message: '请选择有效日期' }]"
                >
                  <!-- <a-config-provider :locale="locale">
                    <a-range-picker v-model:value="mytimer" @change="pickerChange" />
                  </a-config-provider> -->
                  <a-config-provider :locale="zhCN">
                    <a-range-picker
                      v-model:value="formState2['range-picker']"
                      value-format="YYYY-MM-DD"
                      :disabled-date="disabledDate"
                      :disabled="pageType === 4 ? [true, false] : [false, false]"
                      @change="pickerChange"
                    />
                  </a-config-provider>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="支付金额"
                  name="paymentAmount"
                  :rules="[{ required: true, message: '请填写支付金额' }]"
                >
                  <a-input v-model:value="formState2.paymentAmount" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="支付方式"
                  name="paymentMethod"
                  :rules="[{ required: true, message: '请选择支付方式' }]"
                >
                  <a-select
                    ref="select"
                    v-model:value="formState2.paymentMethod"
                    style="width: 100%"
                  >
                    <a-select-option value="Alipay">支付宝</a-select-option>
                    <a-select-option value="WeChat">微信</a-select-option>
                    <a-select-option value="Cash">现金</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <a-table v-else :pagination="false" :dataSource="cardDetailList" :columns="columns">
            <template v-slot:bodyCell="{ column, record, index }">
              <template v-if="column.key === 'index'">
                {{ index + 1 }}
              </template>
              <template v-if="column.key === 'validatorTime'">
                {{ record.cardStartDate }} 至 {{ record.cardEndDate }}
              </template>
              <template v-if="column.key === 'paymentMethod'">
                <span v-if="record.paymentMethod === 'Alipay'">支付宝</span>
                <span v-if="record.paymentMethod === 'WeChat'">微信</span>
                <span v-if="record.paymentMethod === 'Cash'">现金</span>
              </template>
            </template>
          </a-table>
        </a-card>
      </div>
    </div>
    <!-- pageType这个计算属性，只有在页面模板中使用一下，才会被vue添加到响应式依赖里面去，才会动态执行一下计算属性  -->
    <div class="bottom" v-if="pageType !== 3">
      <a-button @click="reset">重置</a-button>
      <a-button type="primary" @click="ok">
        <template v-if="pageType === 1">添加</template>
        <template v-if="pageType === 2">更新</template>
        <template v-if="pageType === 4">缴费</template>
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeftOutlined } from '@ant-design/icons-vue';
import { ref, reactive, computed } from 'vue';
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import 'dayjs/locale/zh-cn';
import dayjs from 'dayjs';
import {
  addParkingCardReqeust,
  getCardDetailReqeust,
  editCardReqeust,
  rechargeCardReqeust,
  getCardDetailListReqeust,
} from '@/apis/cart';

const refForm1 = ref<any>(null);
const refForm2 = ref<any>(null);

const route = useRoute();
const topLeftTitle = ref('');
// 之前有一个业务，4业务，公用同一个UI效果，我自己就写了4个变量，通过route的path的includesd查找，判断4种状态，在写4个业务
// 判断是新增1还是编辑2的页面, 查看是3  重新缴费是 4
// 计算属性，vue3里面有了优化，计算属性，在页面上渲染了，使用了一下以后，才会执行。如果页面不使用
// 那么为了性能的优化，就不会执行这个计算属性，相当于缓存使用之前默认值的效果
const pageType = computed(() => {
  if (route.path.includes('addMonthCard')) {
    // 合理的使用return，就不需要写 else语句

    topLeftTitle.value = '添加月卡';
    console.log(111, topLeftTitle.value);
    return 1;
    // return '添加月卡'
  }
  if (route.path.includes('editMonthCard')) {
    topLeftTitle.value = '编辑月卡';
    return 2;
    // return '编辑月卡'
  }
  if (route.path.includes('viewMonthCard')) {
    topLeftTitle.value = '查看详情';
    return 3;
  }
  if (route.path.includes('renewMonthCard')) {
    topLeftTitle.value = '月卡续费';
    return 4;
  }
  return 1;
});

// 因为编辑需要两个id，我这里就单独定义两个id变量，接受他，页面不需要显示，所以不用ref响应式
let carInfoId: any = null;
let rechargeId: any = null;
const getCardDetail = async () => {
  const res = await getCardDetailReqeust(route.params?.id);
  console.log(res);
  formState1.personName = res.data.personName;
  formState1.phoneNumber = res.data.phoneNumber;
  formState1.carNumber = res.data.carNumber;
  formState1.carBrand = res.data.carBrand;

  if (pageType.value === 2) {
    formState2.cardStartDate = res.data.cardStartDate;
    formState2.cardEndDate = res.data.cardEndDate;
    formState2.paymentAmount = res.data.paymentAmount;
    formState2.paymentMethod = res.data.paymentMethod;
    // 下面这个字段，是专门给 日期范围选择插件使用的，要符合别人插件的格式，数组里面两个字符串
    formState2['range-picker'] = [res.data.cardStartDate, res.data.cardEndDate];
  } else if (pageType.value === 4) {
    formState2.paymentAmount = '';
    formState2.paymentMethod = '';

    // 2024-01-29   V3 版本开始，默认使用 dayjs 替换了 momentjs 库，也可以手动换成momentjs 或者 date-fns 日期库
    // dayjs怎么样将当前时间 添加一天 或者一个月  https://day.js.org/docs/zh-CN/manipulate/add
    formState2.cardStartDate = dayjs().add(1, 'day').format('YYYY-MM-DD');
    formState2.cardEndDate = '';
    formState2['range-picker'] = [formState2.cardStartDate, formState2.cardEndDate];
  }

  // 赋值两个id
  carInfoId = res.data.carInfoId;
  rechargeId = res.data.rechargeId;
};

const cardDetailList = ref<any[]>([]);
const columns = [
  {
    title: '序号',
    key: 'index',
  },
  {
    title: '有效时间',
    // 如果对象数组里面的 值不能直接展示到页面上，需要自己
    // 通过插槽修改一下的属性，就不需要写dataIndex
    key: 'validatorTime',
  },
  {
    title: '支付金额',
    dataIndex: 'paymentAmount',
    key: 'paymentAmount',
  },
  {
    title: '支付方式',
    dataIndex: 'paymentMethod',
    key: 'paymentMethod',
  },
  {
    title: '办理时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '办理人',
    dataIndex: 'createUser',
    key: 'createUser',
  },
];
const getCardDetailList = async () => {
  const res = await getCardDetailListReqeust(route.params?.id);
  formState1.personName = res.data.personName;
  formState1.phoneNumber = res.data.phoneNumber;
  formState1.carNumber = res.data.carNumber;
  formState1.carBrand = res.data.carBrand;
  // 下面缴费的列表数据，也需要保存
  cardDetailList.value = res.data.rechargeList;
};
// 如果是编辑页面就发请求 获取详情
// ref定义的变量需要 .value  计算属性在js里面也需要 .value
if (pageType.value === 2 || pageType.value === 4) {
  getCardDetail();
}

if (pageType.value === 3) {
  // 如果是查看页面，就执行这个请求
  getCardDetailList();
}

// 需要禁用的日期
const disabledDate = (current: any) => {
  // current是dayjs对象
  // console.log(current.format('YYYY-MM-DD'), dayjs().endOf('day').format('YYYY-MM-DD'));
  // 写完代码  一定要自测，不要直接交给测试同学，
  // 每写完一个新功能，就要带上旧功能去测试。例如写完了编辑，就在测试新增+编辑。反复多操作基础
  if (pageType.value === 4) {
    return current && current <= dayjs().endOf('day');
  }
  return false;
};

const formState1 = reactive<any>({
  personName: '',
  phoneNumber: '',
  carNumber: '',
  carBrand: '',
});

const formState2 = reactive<any>({
  cardStartDate: '',
  cardEndDate: '',
  'range-picker': [],
  paymentAmount: '',
  paymentMethod: 'Alipay',
});

const mytimer = ref<any>();
const pickerChange = (date: any, dateString: any) => {
  console.log(date, dateString);
  console.log(mytimer.value);
  formState2.cardStartDate = dateString[0];
  formState2.cardEndDate = dateString[1];
};

const ok = async () => {
  // console.log(formState1, formState2);
  // console.log(refForm1.value, refForm2.value);
  try {
    // 通过查看官网，得知validate方法的函数返回值是一个 promise
    const res1 = await refForm1.value.validate();
    const res2 = await refForm2.value.validate();
    console.log('校验成功才会执行到下面来', res1, res2);

    let res3: any = null;
    if (pageType.value === 1) {
      res3 = await addParkingCardReqeust({
        personName: formState1.personName,
        phoneNumber: formState1.phoneNumber,
        carNumber: formState1.carNumber,
        carBrand: formState1.carBrand,
        cardStartDate: formState2.cardStartDate,
        cardEndDate: formState2.cardEndDate,
        paymentAmount: formState2.paymentAmount,
        paymentMethod: formState2.paymentMethod,
      });
    } else if (pageType.value === 2) {
      res3 = await editCardReqeust({
        personName: formState1.personName,
        phoneNumber: formState1.phoneNumber,
        carNumber: formState1.carNumber,
        carBrand: formState1.carBrand,
        cardStartDate: formState2.cardStartDate,
        cardEndDate: formState2.cardEndDate,
        paymentAmount: formState2.paymentAmount,
        paymentMethod: formState2.paymentMethod,
        carInfoId,
        rechargeId,
      });
    } else if (pageType.value === 4) {
      res3 = await rechargeCardReqeust({
        cardStartDate: formState2.cardStartDate,
        cardEndDate: formState2.cardEndDate,
        paymentAmount: formState2.paymentAmount,
        paymentMethod: formState2.paymentMethod,
        carInfoId,
      });
    }

    if ((res3 as any).code === 10000) {
      goBack();
    }
  } catch (error) {
    console.log('校验失败：', error);
  }
};

const reset = () => {
  // 表单重置以及情况数据的地方
  refForm1.value.resetFields();
  refForm2.value.resetFields();
  // 重置有缺陷，只能将绑定到页面form标签上面的属性，重置
  // 没有绑定的需要手动重置
  formState2.cardStartDate = '';
  formState2.cardEndDate = '';
};

const router = useRouter();
const goBack = () => {
  router.back();
  // router.go(-1)
};
</script>

<style lang="scss">
// 首位固定定位，中间自适应的三种布局方式
.add-card {
  height: 100vh;
  position: relative;
  .top {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 64px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    .left {
      margin-left: 20px;
      span {
        &:nth-child(1) {
        }
        &:nth-child(2) {
          margin: 0 10px;
          cursor: pointer;
        }
        &:nth-child(3) {
          color: #d8dadc;
        }
        &:nth-child(4) {
          margin: 0 10px;
        }
      }
    }
    .right {
      margin-right: 20px;
    }
  }
  .main {
    height: 100vh;
    padding: 64px 0;
    background-color: #f4f6f8;
    .ant-picker-range {
      width: 100%;
    }
  }
  .bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 64px;
    background-color: #fff;
    text-align: center;
    line-height: 64px;
    .ant-btn {
      margin-right: 15px;
    }
  }
}
// .add-card {
//   height: 100vh;
//   overflow: hidden;
//   .top {
//     height: 50px;
//     background-color: red;
//   }
//   .main {
//     background-color: #ccc;
//     height: calc(100vh - 100px);
//     overflow-y: auto;
//   }
//   .bottom {
//     height: 50px;
//     background-color: red;
//   }
// }
// .add-card {
//   display: flex;
//   flex-direction: column;
//   height: 100vh;
//   overflow: hidden;
//   .top {
//     flex: 0 0 50px;
//     background-color: lightcyan;
//   }
//   .main {
//     flex: 1;
//     background-color: #ccc;
//     height: calc(100vh - 100px);
//     overflow-y: auto;
//   }
//   .bottom {
//     flex: 0 0 50px;
//     background-color: lightgoldenrodyellow;
//   }
// }
</style>
